package com.darren.euc.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by yanglas on 2018/3/11.
 */
public class FileUploadUtils {
    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file, HttpServletRequest request,String dir) throws IOException {
        String fileName = file.getOriginalFilename();
        String path=request.getSession().getServletContext().getRealPath(dir+"/");
        //新建
        String moreDir = new Date().getTime()+"/" + String.valueOf(fileName);
        File tempFile = new File(path, moreDir);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        //保存
        file.transferTo(tempFile);
        return dir + "/" + moreDir;
    }


    public static String uploadFile(MultipartFile file,HttpServletRequest request){
        String dir = request.getSession().getServletContext().getRealPath("/") + File.separator + "xls" + File.separator + getFileDir(file.getOriginalFilename()) + File.separator;
        File filePath = new File(dir);
        if (!filePath.exists()) {
            try {
                filePath.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Long num = new Date().getTime();
        Double d = Math.random()*num;
        String fileName = (num + d.longValue() + "_" + file.getOriginalFilename()).replaceAll(" ", "-");
        File newFile =  new File(filePath,fileName);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFile.getPath();
    }

    private static int getFileDir(String name) {
        return name.hashCode() & 0xf;
    }

}
